package com.sywb.chuangyebao.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.utils.HttpUtils;

import org.bining.footstone.log.Logger;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.ApkUtils;
import org.bining.footstone.utils.SharedUtils;
import org.bining.footstone.utils.ToastUtils;
import org.bining.footstone.widget.ProgressWebView;

/**
 * 获取后台接口协议显示
 */

public class WebActivity extends ActionbarActivity {

    ProgressWebView webContent;

    private String title;
    private String webUrl;
    private String cookie;

    private boolean isStartAdvertising;

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.activity_web;
    }

    @SuppressLint("AddJavascriptInterface")
    @Override
    public void initView(Bundle bundle) {
        super.initView(bundle);

        if (bundle != null) {
            title = bundle.getString("p0");
            webUrl = bundle.getString("p1");
            cookie = bundle.getString("p2");
            isStartAdvertising = bundle.getBoolean("p3", false);
        } else {
            title = getIntent().getStringExtra("p0");
            webUrl = getIntent().getStringExtra("p1");
            cookie = getIntent().getStringExtra("p2");
            isStartAdvertising = getIntent().getBooleanExtra("p3", false);
        }

        if (!TextUtils.isEmpty(title)) {
//            if (title.equals("杂志订阅")) {
//                hasActionBar(false);
//            } else {
//                setTitle(title);
//            }
            setTitle(title);
        }

        Logger.e("webUrl:" + webUrl);
        Logger.e("cookie:" + cookie);

        webContent = (ProgressWebView) findViewById(R.id.web_content);

        if (title != null && title.equals("畅谈通")) {
            synCookies(mActivity, cookie);
        }

        initWebView();

        if (title != null && title.equals("畅谈通")) {
            setHtml(webUrl);
        } else if (!TextUtils.isEmpty(webUrl)) {
            setURL(webUrl);
        }
    }

    @Override
    public void initPresenter() {
    }

    /**
     * 同步一下cookie
     * context：上下文
     * url要访问的url
     */
    public void synCookies(Context context, String cookie) {
        try {
            // String url = HttpUtils.getHttpUrl() + Constants.POST_GET_CODE + "?version=" + ApkUtils.getVersionName();
            String url = "http://www.3158.cn";

            CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();

            String cook = cookieManager.getCookie(url);
            System.out.println("getCookie:  -----------" + cook);

            // CookieManager.setAcceptFileSchemeCookies(true);
            // cookieManager.acceptCookie();
            // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // cookieManager.acceptThirdPartyCookies(webContent);
            // }

            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();// 移除
            // cookieManager.removeAllCookie();

            cookieManager.setCookie(url, "_J_SITE=" + cookie + "-android");

            CookieSyncManager.getInstance().sync();

            cook = cookieManager.getCookie(url);
            System.out.println("getCookie:  -----------" + cook);
        } catch (Exception e) {
        }
    }

    /**
     * 设置需展示的Html片段
     */
    private void setHtml(String protocol) {
        if (protocol != null) {
            webContent.getSettings().setDefaultTextEncodingName("utf-8");
            webContent.loadDataWithBaseURL("http://www.3158.cn", protocol, "text/html", "UTF-8", null);
        } else {
            ToastUtils.show(mActivity, "未获取到内容，请稍后重试");
        }
        hideProgress();
    }

    private void setURL(String url) {
        webContent.loadUrl(url);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("p0", title);
        outState.putString("p1", webUrl);
        outState.putString("p2", cookie);
        super.onSaveInstanceState(outState);
    }

    @Override
    public String getStatisticsIdentity() {
        return title;
    }

    /**
     * 初始化WebView
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {

        /**
         * setAllowFileAccess 启用或禁止WebView访问文件数据 setBlockNetworkImage 是否显示网络图像
         * setBuiltInZoomControls 设置是否支持缩放 setCacheMode 设置缓冲的模式
         * setDefaultFontSize 设置默认的字体大小 setDefaultTextEncodingName 设置在解码时使用的默认编码
         * setFixedFontFamily 设置固定使用的字体 setJavaSciptEnabled 设置是否支持Javascript
         * setLayoutAlgorithm 设置布局方式 setLightTouchEnabled 设置用鼠标激活被选项
         * setSupportZoom 设置是否支持变焦
         * */
        WebSettings settings = webContent.getSettings();
        settings.setJavaScriptEnabled(true);// 设置支持javascript脚本
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 1.NARROW_COLUMNS：可能的话使所有列的宽度不超过屏幕宽度；2.NORMAL：正常显示不做任何渲染；3.SINGLE_COLUMN：把所有内容放大webview等宽的一列中
        // settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// 排版适应屏幕
        settings.setDisplayZoomControls(false);
        settings.setAllowFileAccess(true); // 启用或禁止WebView访问文件数据
        settings.setBuiltInZoomControls(false); //  隐藏缩放按钮
        settings.setSupportZoom(true); // 支持缩放
        // settings.setUseWideViewPort(true);// 可任意比例缩放
        settings.setLoadWithOverviewMode(true);//setUseWideViewPort方法设置webview推荐使用的窗口；设置webview加载的页面的模式
        settings.setGeolocationEnabled(true);// 启用地理定位
        settings.setDomStorageEnabled(true);
        settings.setSaveFormData(true);// 保存表单数据
        // settings.setSavePassword(true);
        // settings.setTextZoom(200);
        // settings.setMixedContentMode(1);
//         settings.setAcceptThirdPartyCookies();
        settings.setAllowFileAccess(true);
        settings.setAllowContentAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);

        settings.setBlockNetworkImage(false);//解决图片不显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        webContent.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String webTitle) {
                super.onReceivedTitle(view, title);
                if (TextUtils.isEmpty(title)) {
                    title = webTitle;
                    setTitle(webTitle);
                }
            }
        });

        webContent.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return false;
            }
        });
    }

    @Override
    public void exit() {
        if (isStartAdvertising) {
            toIntentOther();
        }
        super.exit();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && isStartAdvertising) {
            toIntentOther();
        }
        return super.onKeyDown(keyCode, event);
    }

    public void toIntentOther() {
        RxBus.get().post(Manifest.permission.WRITE_SETTINGS, Manifest.permission.WRITE_SETTINGS);
        int lastVersionCode = SharedUtils.getInt(Constants.LASTUSEVERSION, 0);
        int versionCode = ApkUtils.getVersionCode();
        if (lastVersionCode == 0 || lastVersionCode < versionCode) {
            if (lastVersionCode == 50 && versionCode > 50) {
                SharedUtils.put("home_title_selected", "");
                SharedUtils.put("home_title_unselected", "");
            }
            SharedUtils.put(Constants.ISMESSAGENOTICE, true);
            SharedUtils.put(Constants.ISOPENSUOUND, true);
            SharedUtils.put(Constants.ISOPENVIBRATION, true);
            advance(GuideActivity.class);
        } else {
            SharedUtils.put(Constants.LASTUSEVERSION, versionCode);
            advance(MainAtlasActivity.class);
        }
    }

}
